<template>
  <ele-modal :form="true" :width="400" :title="data ? '编辑模块' : '新增模块'" position="center" v-model="visible"
    @open="handelOpen" @close="handelClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
      <el-form-item label="名称:" prop="name">
        <el-input v-model.trim="form.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="编码:" prop="code">
        <el-input v-model.trim="form.code" clearable></el-input>
      </el-form-item>
      <el-form-item label="排序:" prop="sort">
        <el-input-number v-model="form.sort" :min="0" :value-on-clear="0" />
      </el-form-item>
      <el-form-item label="状态:" prop="status">
        <el-switch v-model="form.status" class="ml-2" inline-prompt
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="启用" inactive-text="禁用"
          active-value="1" inactive-value="0" />
      </el-form-item>
      <el-form-item label="备注:" prop="comment">
        <el-input v-model="form.comment" style="width: 600px" :rows="2" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" :loading="loading" @click="save">提交</el-button>
    </template>
  </ele-modal>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue"
import { EleMessage } from "ele-admin-plus";
import type { FormInstance, FormRules } from 'element-plus';
import { useFormData } from '@/utils/use-form-data';
import { add, edit } from '@/api/system/SysModule';
import type { SysModule, AddSysModule } from '@/api/system/SysModule/model';

const props = defineProps<{
  data: SysModule | null
}>()

const emit = defineEmits<{
  (e: 'reload'): void
}>()

const formRef = ref<FormInstance | null>(null);
const loading = ref<boolean>(false)
const visible = defineModel({ type: Boolean });
const { form, assignFields, resetFields } = useFormData<AddSysModule>({
  comment: '', // 备注说明，初始化为空字符串
  name: '',    // 模块名称，初始化为空字符串
  code: '',    // 模块编码，初始化为空字符串
  sort: 0,     // 排序，初始化为0
  status: ''   // 是否启用，初始化为空字符串
})

const rules = reactive<FormRules>({
  name: [
    {
      required: true,
      message: '请输入模块名称',
      type: 'string',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入模块编码',
      type: 'string',
      trigger: 'blur'
    }
  ]
});

const save = () => {
  formRef.value?.validate().then(async () => {
    loading.value = true
    const res = props.data ? await edit({ ...form, id: props.data.id }) : await add(form)
    loading.value = false
    if (res.code == 200) {
      EleMessage.success('成功提交')
      emit('reload')
      visible.value = false
    } else {
      EleMessage.error(res.message)
      return
    }
  })
}

const handelOpen = () => {
  if (props.data) {
    assignFields(props.data)
  }
}

const handelClose = () => {
  resetFields()
  formRef.value?.resetFields()
}

</script>

<style scoped></style>
